<?php
include_once "top.php";
$ownerid = $_GET['ownerid'];
$owner=$db->ig2_want('mae_user','id='.$ownerid.' and is_delete=0');
if(!$owner || $owner['role_type']!=1) tellgoto('','user.php');

$shop=$db->ig2_want('mae_shop','admin_id="'.trim($owner['id']).'" and status=1');
if(!$shop) tellgoto('','user.php');

// 取得分组商品ID
$now = time();
$activeProductSql = "SELECT distinct p.id FROM mae_admin_product p";
$activeProductSql .= " INNER JOIN mae_rel_admin_exchange_activity_product raeap ON raeap.productid = p.id";
$activeProductSql .= " INNER JOIN mae_admin_exchange_activity aea ON aea.id = raeap.activityid";
$activeProductSql .= " INNER JOIN mae_rel_admin_exchange_activity_group raeag ON raeag.activityid = aea.id";
$activeProductSql .= " INNER JOIN mae_group g ON g.id = raeag.groupid";
$activeProductSql .= " INNER JOIN mae_rel_group_shop rgs ON rgs.groupid = g.id";
$activeProductSql .= " INNER JOIN mae_shop s ON s.id = rgs.shopid";
$activeProductSql .= " WHERE aea.starttime <= ".$now." AND aea.endtime >= ".$now." AND aea.status = 1 AND s.id = ".$shop['id'];
$activeProductList = $db->ig2_query_select($activeProductSql);

$where = "1<>1";
if ($activeProductList) {
    $where = " temp.id IN (";
    foreach($activeProductList as $product) {
        $where .= $product['id'].",";
    }
    $where = substr($where, 0, strlen($where) - 1);
    $where .= ")";
}

$product1List = $db->ig2_query_select('SELECT temp.* FROM '.
    '(SELECT * FROM mae_admin_product WHERE status = 1 AND userange = 1 AND isvirtual = 0 AND stock > 0'.
    ' UNION '.
    ' SELECT p.* FROM mae_admin_product p WHERE p.status = 1 AND p.userange = 1 AND p.isvirtual = 1 AND exists(SELECT 1 FROM mae_admin_product_virtual v WHERE v.productid = p.id AND v.isused = 0)) temp'.
    ' WHERE '.$where.
' ORDER BY temp.istop DESC, temp.createtime DESC');

// 普通商品列表
$product2List = $db->ig2_query_select('SELECT temp.* FROM '.
    '(SELECT * FROM mae_admin_product WHERE status = 1 AND userange = 2 AND isvirtual = 0 AND stock > 0'.
    ' UNION '.
    ' SELECT p.* FROM mae_admin_product p WHERE p.status = 1 AND p.userange = 2 AND p.isvirtual = 1 AND exists(SELECT 1 FROM mae_admin_product_virtual v WHERE v.productid = p.id AND v.isused = 0)) temp'.
    ' WHERE '.$where.
    ' ORDER BY temp.istop DESC, temp.createtime DESC');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0,user-scalable=no,maximum-scale=1,width=device-width" />
    <meta content="telephone=no" name="format-detection" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />
    <title>积分商城</title>
    <link href="css/discount.css" rel="stylesheet" type="text/css" />
    <link href="css/common.css" rel="stylesheet" type="text/css" />
    <script src="inc/jquery.min.js" type="text/javascript"></script>
</head>

<body>
<input type="hidden" id="userid" value="<?php echo($ownerid)?>" />
<div class="score_body">
    <div class="score_body_con">
        <div class="score_body_con_box1">积分商城</div>
        <div class="score_body_con_box2">
            <a href="javascript:void(0);" class="product1">促销协销物品</a>
            <a href="javascript:void(0);" class="product2">普通商品</a>
        </div>
        <div class="score_body_con_box3">
            <div class="score_body_con_box3_inner1">
                <div class="score_body_con_box3_inner1_title">
                    洗漱包、自拍杆兑换数量以十个一组为单位，一旦兑换，无法退货。
                </div>
                <div class="score_productlist productleft">
                    <ul>
                        <?php
                        foreach($product1List as $product1) {
                        ?>
                            <li id="product_<?php echo($product1['id'])?>" data-score="<?php echo($product1['score'])?>">
                                <div class="score_liselect"><a href="javascript:void(0)"><img src="images/unselected.png" /></a></div>
                                <div class="score_left_left"><img src="<?php echo($product1['imgurl'])?>" /></div>
                                <div class="score_right_left">
                                    <div class="score_right1_left"><?php echo($product1['name'])?></div>
                                    <div class="score_right3_left"><?php echo($product1['score'])?>积分</div>
                                    <div class="score_right2_left"><a href="javascript:void(0)" class="minusbtn">-</a><span>0</span><a href="javascript:void(0)" class="addbtn">+</a></div>
                                </div>
                            </li>
                        <?php
                        }
                        ?>
                    </ul>
                </div>
            </div>

            <div class="score_body_con_box3_inner2" style="display:none;">
                <div class="score_body_con_box3_inner2_title">
                    店长每月兑换普通商品上限为1500分
                    <!-- 更多店长礼品正在补货中，敬请期待 -->
                </div>
                <div class="score_productlist productright">
                    <ul>
                        <?php
                        foreach($product2List as $product2) {
                            ?>
                            <li id="product_<?php echo($product2['id'])?>" data-score="<?php echo($product2['score'])?>">
                                <div class="score_liselect"><a href="javascript:void(0)"><img src="images/unselected.png" /></a></div>
                                <div class="score_left_right"><img src="<?php echo($product2['imgurl'])?>" /></div>
                                <div class="score_right_right">
                                    <div class="score_right1_right"><?php echo($product2['name'])?></div>
                                    <div class="score_right3_right"><?php echo($product2['score'])?>积分</div>
                                    <div class="score_right2_right"><a href="javascript:void(0)" class="minusbtn">-</a><span>0</span><a href="javascript:void(0)" class="addbtn">+</a></div>
                                </div>
                            </li>
                        <?php
                        }
                        ?>
                    </ul>
                </div>
            </div>

            <div class="score_body_con_box4">
                <div class="score_body_con_box4_inner1" id="usedscore">当前可用积分：<span><?php echo($shop['quadratic'])?></span>分，本次兑换积分<span>0</span>分</div>
                <div class="score_body_con_box4_inner2">
                    <a href="javascript:void(0);" id="commitbtn"><img src="images/score_btnimg.png" />我要兑换</a>
                </div>
                <div class="score_body_con_box4_inner3">本活动最终解释权归壳牌所有</div>
            </div>

        </div>
    </div>
</div>

<div class='pop_mask'style="display:none; width:100%;height:100%"></div>
<div class="exchangepop_body" style="display:none;" id="cancel_con">
    <div class="exchangepop_body_inner">
        <div class="exchangepop_body_cancel"><a href="javascript:void(0)" class="cancel"><img src="images/pop1_cancel.png" width="40" height="40" /></a></div>
        <div class="exchangepop_body_txt">
            <div class="exchangepop_body_txt1">提示</div>
            <div class="exchangepop_body_txt2"></div>
        </div>
        <div class="exchangepop_body_btn"><a href="javascript:void(0)" class="cancel">返回</a></div>
    </div>
</div>
</body>
<script type="text/javascript">
    var usedScore = 0;
    var remainScore = <?php echo($shop['quadratic'])?>;
    var nowScore = <?php echo($shop['quadratic'])?>;

    $(window).load(function(){
        var height1 = $(".score_body_con").height();
        var height3 = $(window).height();
        if(height1>height3){
            $(".score_body_con").css({
                "min-height":height1
            });
        }else{
            $(".score_body_con").css({
                "min-height":height3
            });
            $(".score_body_con_box4").css({
                "margin-top":height3-height1
            });
        };

        $(".score_left_left").find("img").css({"height":$(".score_left_left").find("img").width()*2/3})
        var heightLeft = $(".score_left_left").height() + 12;
        $(".score_right1_left").css({
            "height":(heightLeft*3)/10,
            "line-height":((heightLeft*3)/10)+"px"
        });
        $(".score_right3_left").css({
            "height":(heightLeft*3)/10,
            "line-height":((heightLeft*3)/10)+"px"
        });
        $(".score_right2_left a").css({
            "height":(heightLeft*2)/5,
            "line-height":((heightLeft*2)/5)+"px"
        });
        $(".score_right2_left span").css({
            "height":(heightLeft*2)/5,
            "line-height":((heightLeft*2)/5)+"px"
        });

        $(".product1").click(function(){
            $(".score_body_con_box3_inner1").css({
                "display":"block"
            });
            $(".score_body_con_box3_inner2").css({
                "display":"none"
            });

            $(".score_left_left").find("img").css({"height":$(".score_left_left").find("img").width()*2/3})
            var heightLeft = $(".score_left_left").height() + 12;

            $(".score_right1_left").css({
                "height":(heightLeft*3)/10,
                "line-height":((heightLeft*3)/10)+"px"
            });
            $(".score_right3_left").css({
                "height":(heightLeft*3)/10,
                "line-height":((heightLeft*3)/10)+"px"
            });
            $(".score_right2_left a").css({
                "height":(heightLeft*2)/5,
                "line-height":((heightLeft*2)/5)+"px"
            });
            $(".score_right2_left span").css({
                "height":(heightLeft*2)/5,
                "line-height":((heightLeft*2)/5)+"px"
            });

            $(this).css({
                "background":"#d21420"
            });
            $(this).next().css({
                "background":"#808080"
            });
        });
        $(".product2").click(function(){
            $(".score_body_con_box3_inner2").css({
                "display":"block"
            });
            $(".score_body_con_box3_inner1").css({
                "display":"none"
            });

            $(".score_left_right").find("img").css({"height":$(".score_left_right").find("img").width()*2/3});
            var heightRight = $(".score_left_right").height() + 12;
            $(".score_right1_right").css({
                "height":(heightRight*3)/10,
                "line-height":((heightRight*3)/10)+"px"
            });
            $(".score_right3_right").css({
                "height":(heightRight*3)/10,
                "line-height":((heightRight*3)/10)+"px"
            });
            $(".score_right2_right a").css({
                "height":(heightRight*2)/5,
                "line-height":((heightRight*2)/5)+"px"
            });
            $(".score_right2_right span").css({
                "height":(heightRight*2)/5,
                "line-height":((heightRight*2)/5)+"px"
            });

            $(this).css({
                "background":"#d21420"
            });
            $(this).prev().css({
                "background":"#808080"
            });
        });

        // 浮层关闭
        $(".cancel").bind("click", function(){
            $(".exchangepop_body").fadeOut(500);
            $(".pop_mask").fadeOut(500);
        });

        // 增加按钮逻辑
        $(".addbtn").bind("click", function(){
            var productId = $(this).parents("li").attr("id").substring(8);
            var productScore = parseInt($(this).parents("li").data("score"));
            var currentNum = parseInt($(this).parent("div").children("span").text());

            currentNum++;
            usedScore += productScore;
            nowScore -= productScore;

            // 如果使用的积分大于剩余的积分了
            if (usedScore > remainScore) {
                popup("您的积分不足，无法兑换所选商品！");

                usedScore -= productScore;
                nowScore += productScore;
            } else {
                $(this).parent("div").children("span").text(currentNum);
                $("#usedscore").html("当前可用积分：<span>" + nowScore + "</span>分，本次兑换积分<span>" + usedScore + "</span>分");
                if (currentNum > 0) {
                    $(this).parents("li").find(".score_liselect img").attr("src", "images/selected.png");
                }
            }
        });

        // 减少按钮逻辑
        $(".minusbtn").bind("click", function(){
            var productId = $(this).parents("li").attr("id").substring(8);
            var productScore = parseInt($(this).parents("li").data("score"));
            var currentNum = parseInt($(this).parent("div").children("span").text());

            if (currentNum >= 1) {
                currentNum--;
                usedScore -= productScore;
                nowScore += productScore;
                $(this).parent("div").children("span").text(currentNum);
                $("#usedscore").html("当前可用积分：<span>" + nowScore + "</span>分，本次兑换积分<span>" + usedScore + "</span>分");

                if (currentNum <= 0) {
                    $(this).parents("li").find(".score_liselect img").attr("src", "images/unselected.png");
                }
            }
        });

        // 确认按钮
        $("#commitbtn").bind("click", function(){
            $(this).css({'background':'#F8D62E'});
            // 遍历数量大于0的商品
            var selectedArray = [];
            var totalnum = 0;
            $(".productleft").find("li").each(function(){
                var productId = $(this).attr("id").substring(8);
                var num = parseInt($(this).find("span").text());

                if (num > 0) {
                    var selectedObject = {};
                    selectedObject.productid = productId;
                    selectedObject.num = num;
                    selectedObject.type = 1;
                    selectedArray.push(selectedObject);
                    totalnum += num;
                }
            });

            $(".productright").find("li").each(function(){
                var productId = $(this).attr("id").substring(8);
                var num = parseInt($(this).find("span").text());

                if (num > 0) {
                    var selectedObject = {};
                    selectedObject.productid = productId;
                    selectedObject.num = num;
                    selectedObject.type = 2;
                    selectedArray.push(selectedObject);
                    totalnum += num;
                }
            });

            if (totalnum == 0) {
                alert('请选择商品');
                $(this).css({'background': '#F09802'});
                return;
            }
            if (totalnum > 0) {
                $.ajax({
                    type: "GET",
                    url: "ra_ajax_market.php",
                    dataType: 'json',
                    data: {
                        method: "checkStatus",
                        userid: $("#userid").val(),
                        selectedarray: JSON.stringify(selectedArray)
                    },
                    success: function(data){
                        if (data.errcode == 1) {
                            popup(data.errmsg);
                        } else {
                            window.location.href="shopowner_market_commit.php?userid=" + $("#userid").val() + "&shopid=" + $("#shopid").val() + "&totalscore=" + usedScore + "&totalnum=" + totalnum + "&selectedarray=" + JSON.stringify(selectedArray)
                        }
                    }
                });
            }
        });
    });

    function popup(msg) {
        $("#cancel_con .exchangepop_body_txt2").html(msg);
        var popupWidth =  $(".score_body_con").width();
        var windowWidth =  $(window).outerWidth();
        var windowHeight =  $(window).outerHeight();
        var popupHeight = $("#cancel_con").height();
        $(".pop_mask").fadeIn(500);
        $("#cancel_con").css({"position": "absolute", "width":popupWidth+"px"}).animate({left: windowWidth/2-popupWidth/2, top: windowHeight/2-popupHeight/2, opacity: "show" }, "slow");
    }
</script>
</html>
